package com.inossem.warehousestorage_inossem.activity.refund_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.inossem.utils.base.ArithUtils;
import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.refund_storage.extra.RefundStorageExtra;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStoragePickingOverviewBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.RefundStorageUtils;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.util.List;

//物料信息
public class RefundStoragePickingMaterielDetailActivity extends BaseActivity {

    private static final String TYPE_SERIAL = "serial";

    private static final String TYPE_INDEX = "index";

    private TextView title, serialNumber, materielCode, materielDescription, inventoryAddress, referencePrice, reservationNumber, reservationRowItem, purchaseOrder, purchaseOrderRowNumber, outStorageNumber, hadRefundStorageNumber, batchNumber, pageInfo, showAndHide;

    private EditText refundStorageNumber;

    private Button previous, next;

    private String serialNumberStr, unit, mMaterielCode , mRetainDecimal;

    private int index;

    private RefundStoragePickingOverviewBean.OutputInfoBodyBean.ItemListBean materielItem;

    private PercentLinearLayout batchLayout;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_refund_storage_picking_materiel_detail);
        initView(RefundStoragePickingMaterielDetailActivity.this);
        initData(RefundStoragePickingMaterielDetailActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);

        serialNumber = (TextView) activity.findViewById(R.id.serialNumber);
        materielCode = (TextView) activity.findViewById(R.id.materielCode);
        materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        inventoryAddress = (TextView) activity.findViewById(R.id.inventoryAddress);
        referencePrice = (TextView) activity.findViewById(R.id.referencePrice);
        reservationNumber = (TextView) activity.findViewById(R.id.reservationNumber);
        reservationRowItem = (TextView) activity.findViewById(R.id.reservationRowItem);
        purchaseOrder = (TextView) activity.findViewById(R.id.purchaseOrder);
        purchaseOrderRowNumber = (TextView) activity.findViewById(R.id.purchaseOrderRowNumber);
        outStorageNumber = (TextView) activity.findViewById(R.id.outStorageNumber);
        hadRefundStorageNumber = (TextView) activity.findViewById(R.id.hadRefundStorageNumber);
        batchNumber = (TextView) activity.findViewById(R.id.batchNumber);
        pageInfo = (TextView) activity.findViewById(R.id.pageInfo);
        showAndHide = (TextView) activity.findViewById(R.id.showAndHide);
        refundStorageNumber = (EditText) activity.findViewById(R.id.refundStorageNumber);
        previous = (Button) activity.findViewById(R.id.previous);
        next = (Button) activity.findViewById(R.id.next);
        batchLayout = (PercentLinearLayout) activity.findViewById(R.id.batchLayout);
    }

    private void initData(BaseActivity activity) {
        title.setText(activity.getResources().getString(R.string.activity_receive_materiel_detail_title));
        ActivityUtils.initBackAndFunction(activity, getResources().getString(R.string.activity_in_storage_allocating_add_operator_overview), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                backAndUpdate(activity);
            }
        });
        refundStorageNumber.setOnFocusChangeListener((View v, boolean hasFocus) -> {
            if (hasFocus) {
                refundStorageNumber.setText("");
            }
        });
        previous.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index > 0) {
                    index--;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        next.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index < (RefundStorageUtils.getPickingMaterielListSize(activity) - 1)) {
                    index++;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        showAndHide.setOnClickListener((View v) -> {
            if (batchLayout.getVisibility() == View.GONE) {
                batchLayout.setVisibility(View.VISIBLE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_hide_information));
            } else if (batchLayout.getVisibility() == View.VISIBLE) {
                batchLayout.setVisibility(View.GONE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_show_information));
            }
        });
        getExtra(activity);
        getIndexBySerial(activity, serialNumberStr);
        getData(activity, TYPE_SERIAL);
        setmScanListener((String scanResult, int length) -> {
            mMaterielCode = QRCodeUtils.DecryptQRCode(scanResult);
            int indexTemp = RefundStorageUtils.getPickingIndexByMaterielCode(activity, mMaterielCode);
            if (indexTemp != -1) {
                if (indexTemp != index) {
                    index = indexTemp;
                    changeAndUpdate(activity);
                }
            } else {
                Utils.middleToast(activity, getResources().getString(R.string.activity_in_storage_receive_materiel_detail_not_find) + mMaterielCode + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_materiel));
            }
        }, QRCodeConstant.TYPE_MATERIEL_CODE);
    }

    private void getExtra(Activity activity) {
        serialNumberStr = activity.getIntent().getStringExtra(RefundStorageExtra.SERIAL);
    }

    private void getIndexBySerial(Context context, String serialNumber) {
        index = RefundStorageUtils.getPickingIndexBySerial(context, serialNumber);
    }

    private void getData(BaseActivity context, String getMaterielInformationFromType) {
        switch (getMaterielInformationFromType) {
            case TYPE_SERIAL:
                materielItem = RefundStorageUtils.getPickingMaterielInformationBySerial(context, serialNumberStr);
                break;
            case TYPE_INDEX:
                materielItem = RefundStorageUtils.getPickingMaterielInformationByIndex(context, index);
                break;
        }
        unit = materielItem.getUnit_name();
        serialNumber.setText(materielItem.getRid());
        materielCode.setText(materielItem.getMat_code());
        mRetainDecimal = materielItem.getDecimal_place();
        materielDescription.setText(materielItem.getMat_name());
        inventoryAddress.setText(materielItem.getLocation_code() + "-" + materielItem.getLocation_name());
        referencePrice.setText(materielItem.getRefer_price());
        reservationNumber.setText(materielItem.getReserve_id());
        reservationRowItem.setText(materielItem.getReserve_rid());
        purchaseOrder.setText(materielItem.getPurchase_order_code());
        purchaseOrderRowNumber.setText(materielItem.getPurchase_order_rid());
        outStorageNumber.setText(materielItem.getOutput_qty() + unit);
        hadRefundStorageNumber.setText(materielItem.getHave_return_qty() + unit);
        refundStorageNumber.setText(TextUtils.isEmpty(materielItem.getRefundNumber()) ? "" : (materielItem.getRefundNumber() + unit));
        batchNumber.setText(TextUtils.isEmpty(materielItem.getBatch()) ? materielItem.getBatch_list().get(0).getBatch() : materielItem.getBatch());
        initBatchInfo(context, TextUtils.isEmpty(materielItem.getBatch()) ? materielItem.getBatch_list().get(0).getBatch_spec_list() : getBatchInfo(materielItem.getBatch_list(), materielItem.getBatch()));
        if (materielItem.getBatch_list().size() > 1) {
            batchNumber.setTextColor(ContextCompat.getColor(context, R.color.activity_receive_delivery_overview_font_color));
            batchNumber.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    DialogUtils.getRefundStoragePickingBatchDialog(context, materielItem.getBatch_list(), new DialogUtils.RefundStoragePickingBatchNumberListener() {
                        @Override
                        public void onSelect(Dialog dialog, String batchNumberStr, List<RefundStoragePickingOverviewBean.OutputInfoBodyBean.ItemListBean.BatchListBean.BatchSpecListBean> batchInfoList) {
                            batchNumber.setText(batchNumberStr);
//                            initBatchInfo(context, batchInfoList);
                        }
                    }).show();
                }
            });
        } else {
            batchNumber.setTextColor(ContextCompat.getColor(context, R.color.common_font_content));
            batchNumber.setOnClickListener(null);
        }

        pageInfo.setText(RefundStorageUtils.getPickingMaterielListSize(context) + " | " + (index + 1));
        if (index <= 0) {
            previous.setText(getResources().getString(R.string.activity_in_storage_receive_materiel_detail_return));
        } else {
            previous.setText(getResources().getString(R.string.activity_in_storage_receive_materiel_detail_previous));
        }
        if (index >= (RefundStorageUtils.getPickingMaterielListSize(context) - 1)) {
            next.setText(getResources().getString(R.string.activity_in_storage_receive_materiel_detail_return));
        } else {
            next.setText(getResources().getString(R.string.activity_in_storage_receive_materiel_detail_next));
        }
    }

    private List<RefundStoragePickingOverviewBean.OutputInfoBodyBean.ItemListBean.BatchListBean.BatchSpecListBean> getBatchInfo(List<RefundStoragePickingOverviewBean.OutputInfoBodyBean.ItemListBean.BatchListBean> batchList, String batchNumber) {
        for (int i = 0; i < batchList.size(); i++) {
            RefundStoragePickingOverviewBean.OutputInfoBodyBean.ItemListBean.BatchListBean batchInfo = batchList.get(i);
            if (batchInfo.getBatch().equals(batchNumber)) {
                return batchInfo.getBatch_spec_list();
            }
        }
        return null;
    }

    private void initBatchInfo(Context context, List<RefundStoragePickingOverviewBean.OutputInfoBodyBean.ItemListBean.BatchListBean.BatchSpecListBean> batchInfoList) {
        if (batchInfoList != null && !batchInfoList.isEmpty()) {
            batchLayout.removeAllViews();
            for (int i = 0; i < batchInfoList.size(); i++) {
                RefundStoragePickingOverviewBean.OutputInfoBodyBean.ItemListBean.BatchListBean.BatchSpecListBean batchInfo = batchInfoList.get(i);
                RefundStorageUtils.createTextView(context, batchLayout, batchInfo.getBatch_spec_name(), batchInfo.getBatch_spec_value());
            }
        }
    }

    private void updateInfo(Context context) {
        materielItem.setRefundNumber(refundStorageNumber.getText().toString().replace(materielItem.getUnit_name(), "").trim());
        materielItem.setBatch(batchNumber.getText().toString());
        RefundStorageUtils.updatePickingRefundStorageItem(context, materielItem);
    }

    private String check(Context context) {
        String refundStorageNumberStr = refundStorageNumber.getText().toString().replace(materielItem.getUnit_name(), "").trim();
//        if (TextUtils.isEmpty(refundStorageNumberStr)) {
//            return "退库数量不可以为空";
//        }

        if (!TextUtils.isEmpty(refundStorageNumberStr) && !RegexUtils.checkDecimal(refundStorageNumberStr)) {
            return getResources().getString(R.string.activity_refund_storage_picking_materiel_detail_the_number_of_restores_is_illegal);
        }

        if (!TextUtils.isEmpty(refundStorageNumberStr) && RegexUtils.checkZero(refundStorageNumberStr)) {
            return getResources().getString(R.string.activity_refund_storage_picking_materiel_detail_the_number_of_restores_must_be_greater_than_zero);
        }
        if (!TextUtils.isEmpty(refundStorageNumberStr) &&!Utils.checkRetainDecimal(refundStorageNumberStr, mRetainDecimal)) {
//            Utils.middleToast(context, context.getResources().getString(R.string.activity_in_storage_receive_overview_serial) + serialNumber + );
            return String.format(context.getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(mRetainDecimal) ? context.getResources().getString(R.string.common_retain_decimal_unlimited) : mRetainDecimal);
        }

        if (!TextUtils.isEmpty(refundStorageNumberStr)) {
            float maxNumber = ArithUtils.sub(materielItem.getOutput_qty(), materielItem.getHave_return_qty()).floatValue();
            float refundStoragetNumberFloat = Float.parseFloat(refundStorageNumberStr);
            if (refundStoragetNumberFloat > maxNumber) {
                return getResources().getString(R.string.activity_refund_storage_picking_materiel_detail_the_number_of_restores_can_not_be_greater_than_the_number_of_outgoing_libraries_minus_the_number_of_restores);
            }
        }

        return null;
    }

    private void backAndUpdate(Context context) {
        String checkResult = check(context);
        if (checkResult == null) {
            updateInfo(context);
            super.onBackPressed();
        } else {
            DialogUtils.getConfirmDialog(context, checkResult + "\n" + getResources().getString(R.string.activity_receive_materiel_detail_force_back), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    RefundStoragePickingMaterielDetailActivity.super.onBackPressed();
                }
            }).show();
        }
    }

    private void changeAndUpdate(BaseActivity activity) {
        String checkResult = check(activity);
        if (checkResult == null) {
            updateInfo(activity);
            getData(activity, TYPE_INDEX);
        } else {
            DialogUtils.getConfirmDialog(activity, checkResult + "\n" + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_force_switch), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    getData(activity, TYPE_INDEX);
                }
            }).show();
        }
    }

    @Override
    public void onBackPressed() {
        backAndUpdate(RefundStoragePickingMaterielDetailActivity.this);
    }
}
